import { Provide } from '@midwayjs/decorator';

@Provide()
export class Tree {
  async deepTree(list, op) {
    if (!list || !list.length) return [];
    const newList = [];
    const map = {};
    let parentId = 'parentId';
    let sort = 'sort_order';
    if (op) {
      parentId = op.parentId;
      sort = op.sort;
    }
    list.forEach(e => (map[e.id] = e));

    list.forEach(e => {
      const parent = map[e[parentId]];

      if (parent) {
        (parent.children || (parent.children = [])).push(e);
      } else {
        newList.push(e);
      }
    });

    const fn = list => {
      list.map(e => {
        if (e.children instanceof Array) {
          e.children = this.orderBy(e.children, sort, 'desc');

          fn(e.children);
        }
      });
    };

    fn(newList);

    return this.orderBy(newList, sort, 'desc');
  }

  orderBy(list, key, type = 'asc') {
    return list.sort((a, b) =>
      type === 'asc' ? a[key] - b[key] : b[key] - a[key]
    );
  }
}
